package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostDubbleEvent;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.common.QueryUserUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsOrderRetChangeSaveCmd;
import com.jackrain.nea.fc.dl.mapper.WmsOrderInMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;

/**
 * wms 采购退改单->fc
 *
 * @author kangcong
 * @date 2018/10/24
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsOrderRetChangeSaveCmdImpl extends CommandAdapter implements WmsOrderRetChangeSaveCmd {
    @Autowired
    PostDubbleEvent postDubbleEvent;
    @Autowired
    PostHandleEvent postHandleEvent;
    @Autowired
    QueryCpUtil postQueryEvemt;
    @Autowired
    QueryUserUtil postUserEvent;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsOrderInMapper wmsOrderInMapper = ApplicationContextHandle.getBean(WmsOrderInMapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0 || param.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
//        log.debug("----------出库回传（采购退货单改单）----------" + param);
        log.info("WmsOrderRetChangeSaveCmdImpl--param-->{}",param);

        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();

        JSONArray dataArray = param.getJSONArray("data");
        JSONArray succesIdArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray errArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject dataJo = dataArray.getJSONObject(i);
            JSONObject oldJo = dataJo.getJSONObject("DL_B_PUR_RET");
//            JSONArray purInItemArray = dataJo.getJSONArray("DL_B_PUR_RET_ITEM");
            boolean falg = dataJo.getBoolean("flag");
            dataJo.remove("flag");
            String billnoid = oldJo.getString("ID");
            String billno = oldJo.getString("BILL_NO");

            JSONObject stateObj = new JSONObject();
            //根据单号查询objjid
            Long objid = wmsOrderInMapper.selectPurRetObjidByBillNo(billno);

            try {

//                JSONObject fixColumn = dataConversion(oldJo, purInItemArray);
                User user = postUserEvent.getUser(UserInformation.USER_NAME);
                JSONObject resultJson = new JSONObject();
                resultJson.put("objid", objid);
//                resultJson.put("fixcolumn", fixColumn);
                resultJson.put("table", "DL_B_PUR_RET");
                resultJson.put("isWMSCheck", "N");
//                log.info("SaveJson==>" + resultJson.toString());
                accesLogger.info("WmsOrderRetChangeSaveCmdImpl--resultJson-->{}",resultJson);

                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlOrderOut", new HashMap(16));
                event.put("param", resultJson);
                querySession.setEvent(event);

//                //保存服务
//                if (objid != null) {
////
////                    JSONObject retJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
////                    if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
////                        throw new NDSException("保存失败:" + retJo.get("message") + retJo.get("error") + retJo.get("data"));
////                    }
////                    objid = retJo.getLong("objid");
////                    if (objid == null) {
////                        JSONObject retData = retJo.getJSONObject("data");
////                        objid = retData.getLong("objid");
////                    }
//                    stateObj.put("id", billnoid);
//                    stateObj.put("objid", objid);
//                    succesIdArray.add(stateObj);
//                }else{
//                    throw new NDSException("查询失败:单据" + billno+" 不存在或不符合发出所需的单据状态");
//                }

                if (objid == null) {
                    throw new NDSException("查询失败:单据" + billno + " 不存在或不符合发出所需的单据状态");
                }

                if (falg == false) {
                    stateObj.put("id", billnoid);
                    stateObj.put("objid", objid);
                    succesIdArray.add(stateObj);
                }
                if (falg == true ) {
                    resultJson.put("objid", objid);
                    resultJson.put("CARRIER_NAME", "WMS");
                    resultJson.put("isWmsSendOut", "Y");
                    resultJson.put("LOGISTICS_BILL_NO", billno);
//                    log.info("SendOutJson==>" + resultJson.toString());
                    accesLogger.info("WmsOrderRetChangeSaveCmdImpl--resultJson_sendout-->{}",resultJson);

                    event.setParameter("command", "com.jackrain.nea.dl.pur.api.ret.PurRetSendOutCmd:1.0:dl");
                    event.setParameter("table", "DL_B_PUR_RET");
                    event.setParameter("webaction", "PUR_RET_SEND_OUT");
                    event.put("param", resultJson);
                    querySession.setEvent(event);
                    JSONObject accJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "webaction");
                    accesLogger.info("WmsOrderRetChangeSaveCmdImpl--accJo-->{}",accJo);

                    if (accJo.get("code") != null && (int) accJo.get("code") < 0) {
                        throw new NDSException("发出失败:" + accJo.get("message") + accJo.get("error") + accJo.get("data"));
                    }
                    queryDataArray.add(resultJson);
                    stateObj.put("id", billnoid);
                    stateObj.put("objid", objid);
                    succesIdArray.add(stateObj);
                }

            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("id", billnoid);
                errrobj.put("objid", objid);
                errArray.add(errrobj);
            }
        }

        if (errArray.size() > 0) {
            vh.put("error", errArray);
            vh.put("success", succesIdArray);
            vh.put("code", -1);
        } else {
            vh.put("success", succesIdArray);
            vh.put("code", 0);
        }
        vh.put("queryDataArray",queryDataArray);
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
//        log.debug("---------采购退货单执行时间--------->>" + spendTime);
        return vh;

    }

    public JSONObject dataConversion(JSONObject oldJo, JSONArray purInItemArray) {

        String billno = oldJo.getString("BILL_NO");
        //翻译主表
        JSONObject newJo = new JSONObject();
        newJo.put("BILL_NO", billno);
        newJo.put("FROM_BILL_NO", oldJo.getString("WMS_BILL_NO"));
        newJo.put("REFUND_TYPE", "1");
        newJo.put("BILL_DATE", dateToStrLong(oldJo.getDate("DATE_OUT")));
        newJo.put("WMS_OUT", "Y");

        String origecode = oldJo.getString("ORIG_ECODE");
        JSONObject whereJo1 = new JSONObject();
        whereJo1.put("ECODE", origecode);
        JSONObject cpmap1 = postQueryEvemt.queryCP("CP_C_STORE", "ID", whereJo1);
        if (cpmap1 == null) {
            throw new NDSException(origecode + "找不到对应的店仓ID！");
        }
        Long supploerid = TypeUtils.castToLong(cpmap1.getLong("ID"));
        newJo.put("CP_C_STORE_ID", supploerid);
        String destecode = oldJo.getString("DEST_ECODE");
        JSONObject whereJo2 = new JSONObject();
        whereJo2.put("ECODE", destecode);
        JSONObject cpmap2 = postQueryEvemt.queryCP("CP_C_SUPPLIER", "ID", whereJo2);
        if (cpmap2 == null) {
            throw new NDSException(destecode + "找不到对应的供应商ID！");
        }
        Long cpstoreid = TypeUtils.castToLong(cpmap2.getLong("ID"));
        newJo.put("CP_C_SUPPLIER_ID", cpstoreid);

        newJo.put("REMARK", oldJo.getString("REMARK"));
        newJo.put("OWNERENAME", oldJo.getString("OWNER_ENAME"));
        newJo.put("OWNERNAME", oldJo.getString("OWNER_NAME"));

        JSONObject whereJo3 = new JSONObject();
        whereJo3.put("NAME", UserInformation.USER_NAME);
        JSONObject cpmap3 = postQueryEvemt.queryCP("USERS", "ID", whereJo3);
        if (cpmap3 == null) {
            throw new NDSException(UserInformation.USER_NAME + "找不到对应的用户ID！");
        }
        Long ownerid = TypeUtils.castToLong(cpmap3.getLong("ID"));
        newJo.put("OWNERID", ownerid);
        newJo.put("MODIFIERID", ownerid);

        newJo.put("isWMSCheck", "N");
        newJo.put("MODIFIERENAME", oldJo.getString("MODIFIER_ENAME"));
        newJo.put("MODIFIERNAME", oldJo.getString("MODIFIER_NAME"));

        JSONArray itemArray = new JSONArray();
        for (int a = 0; a < purInItemArray.size(); a++) {

            JSONObject oldItemJo = purInItemArray.getJSONObject(a);
            JSONObject newItemJo = new JSONObject();
            String skuecode = oldItemJo.getString("SKU");
            JSONObject whereJo5 = new JSONObject();
            whereJo5.put("ECODE", skuecode);
            whereJo5.put("CP_C_DISTRIB_ID", "0");
            JSONObject cpmap5 = postQueryEvemt.queryCP("PS_C_SKU", "ID", whereJo5);
            if (cpmap5 == null) {
                throw new NoSuchFieldError(skuecode + "查询不到条码信息！");
            }
            Long skuId = TypeUtils.castToLong(cpmap5.getLong("ID"));
            newItemJo.put("PS_C_SKU_ID", skuId);
            newItemJo.put("QTY_BILL", oldItemJo.getString("QTY_OUT"));
            newItemJo.put("QTY_OUT", oldItemJo.getString("QTY_OUT"));
            itemArray.add(newItemJo);

        }
        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_PUR_RET", newJo);
        fixColumn.put("DL_B_PUR_RET_ITEM", itemArray);

        return fixColumn;

    }

    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

}